package com.mubai.files.service.impl;

import java.util.List;

import com.mubai.common.exception.BusinessException;
import com.mubai.files.domain.FilePlay;
import com.mubai.files.service.FilePlayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mubai.files.mapper.FileChannelMapper;
import com.mubai.files.domain.FileChannel;
import com.mubai.files.service.FileChannelService;
import com.mubai.common.support.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 文件通道 服务层实现
 *
 * @author baichuanping
 * @date 2019-01-19
 */
@Service
public class FileChannelServiceImpl implements FileChannelService
{
	@Autowired
	private FileChannelMapper fileChannelMapper;

	@Autowired
	private FilePlayService filePlayService;
	/**
	 * 查询文件通道信息
	 *
	 * @param channelId 文件通道ID
	 * @return 文件通道信息
	 */
	@Override
	public FileChannel selectFileChannelById(Long channelId)
	{
		return fileChannelMapper.selectFileChannelById(channelId);
	}

	/**
	 * 查询文件通道列表
	 *
	 * @param fileChannel 文件通道信息
	 * @return 文件通道集合
	 */
	@Override
	public List<FileChannel> selectFileChannelList(FileChannel fileChannel)
	{
		return fileChannelMapper.selectFileChannelList(fileChannel);
	}

	/**
	 * 新增文件通道
	 *
	 * @param fileChannel 文件通道信息
	 * @return 结果
	 */
	@Override
	public int insertFileChannel(FileChannel fileChannel)
	{
		return fileChannelMapper.insertFileChannel(fileChannel);
	}

	/**
	 * 修改文件通道
	 *
	 * @param fileChannel 文件通道信息
	 * @return 结果
	 */
	@Override
	public int updateFileChannel(FileChannel fileChannel)
	{
		return fileChannelMapper.updateFileChannel(fileChannel);
	}

	/**
	 * 删除文件通道对象
	 *
	 * @param ids 需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteFileChannelByIds(String ids)
	{
		return fileChannelMapper.deleteFileChannelByIds(Convert.toStrArray(ids));
	}

	/**
	 * 删除对应的播放文件
	 * @param ids
	 * @return
	 */
	@Transactional
	@Override
	public int removeFile(String ids) {
		int result = 0;
		String[] idArr = ids.split(",");
		Long id =Long.valueOf(idArr[0]);
		FilePlay filePlay = filePlayService.selectFilePlayById(id);
		if (filePlay == null){
			throw new BusinessException("文件已被删除，请刷新后重试！" );
		}
		result = filePlayService.deleteFilePlayByIds(ids);
		if (result > 0) {
			result=filePlayService.updatePayLimit(filePlay.getChannelCode(),result,filePlay.getOrderNum());
		}else {
			throw new BusinessException("文件删除失败！" );
		}
		return result;
}

	@Override
	public int saveLimit(String ids) {
		String[] idArr = ids.split(",");
		Long id = 0l;
		for (int i = 0 ; i < idArr.length ; i ++){
			id = Long.valueOf(idArr[i]);
			FilePlay order = filePlayService.selectFilePlayById(id);
			if (order == null) continue;;
			order.setOrderNum(i+1);
			filePlayService.updateFilePlay(order);
		}
		return 1;
	}

}